import { ref, markRaw, onMounted } from 'vue';
import { GetTaskDataSummaryListParams } from '@/apis/eci/carbonManagement/model/dataListModel';
import { getTaskDataCalculationList } from '@/apis/eci/carbonManagement/dataList';
import { thousandFormat, transformUnitKgToT } from '@/utils';
import { SearchOptionsType } from '@/components/CPageTable';
import { useRoute } from 'vue-router';
import { useCellRowMerge } from '@/hooks/useCellRowMerge';
import { VxeTablePropTypes } from '@xfchenju/vxe-table';

export const useList = (props: any) => {
  const route = useRoute();
  const loading = ref(false);
  const cellMergeMap = ref<Record<string, any>>({});
  const mergeCellsList = ref<VxeTablePropTypes.MergeCells>([]);
  const { handleCellMerge, handleTransformMapToList } = useCellRowMerge();
  const dataSource = ref<any[]>([]);
  // 页面标题
  const taskNo = route.query.taskNo as any;
  // 搜索配置
  const searchOptions: SearchOptionsType[] = markRaw([]);
  const fields = ['emissionScope', 'emissionCategory', 'ghgSourceName', 'dataNo'];
  const fieldToColMap = {
    emissionScope: 0,
    emissionCategory: 1,
    ghgSourceName: 2,
    dataNo: [3, 4, 5, 6, 11]
  };
  onMounted(() => {
    loadData();
  });
  function loadData() {
    const params: GetTaskDataSummaryListParams = {
      taskNo,
      standard: props.standard
    };
    loading.value = true;
    getTaskDataCalculationList(params)
      .then((res: any) => {
        if (res) {
          cellMergeMap.value = handleCellMerge(res, fields);
          mergeCellsList.value = handleTransformMapToList(cellMergeMap.value, fieldToColMap);
          dataSource.value = res;
        } else {
          dataSource.value = [];
        }
        loading.value = false;
      })
      .catch(error => {
        console.log('error', error);
        loading.value = false;
        dataSource.value = [];
      });
  }

  const mergeCells = ref([{ row: 0, col: 4, rowspan: 1, colspan: 4 }]);
  const sumNum = (list: any[], field: string) => {
    let count = 0;
    list.forEach(item => {
      count += Number(item[field]);
    });

    return thousandFormat(transformUnitKgToT(count, 5));
  };
  const footerMethod = ({ columns, data }: any) => {
    if (!dataSource.value.length) return new Array(columns.length);
    const footerData = [
      columns.map((column: any, _columnIndex: number) => {
        if (_columnIndex === 0) {
          return '绝对排放量';
        }
        if (['proportion'].includes(column.field)) {
          return '100';
        }
        if (['carbonDioxideEquivalent'].includes(column.field)) {
          return sumNum(data, column.field);
        }
        return null;
      })
    ];
    return footerData;
  };

  const extraTableOption = {
    mergeFooterItem: mergeCells.value,
    footerMethod: footerMethod,
    showFooter: true,
    maxHeight: '490'
  };
  return {
    // 头部右侧筛选项配置
    searchOptions,
    loadData,
    dataSource,
    loading,
    extraTableOption,
    mergeCellsList
  };
};
